package com.itheima.utils;

import com.itheima.config.MinioConfig;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Component
@Slf4j
public class MinioUtil {

    private static MinioClient minioClient;

    private static String endpoint;
    private static String accessKey;
    private static String secretKey;
    private static String bucketName;

    public MinioUtil() {

    }

    public MinioUtil(String endpoint, String accessKey, String secretKey, String bucketName) {
        MinioUtil.endpoint = endpoint;
        MinioUtil.accessKey = accessKey;
        MinioUtil.secretKey = secretKey;
        MinioUtil.bucketName = bucketName;
        createMinioClient();
    }

    /**
     * 创建MinioClient
     */
    public static void createMinioClient() {
        try {
            if (minioClient == null) {
                log.info("开始创建 MinioClient...");
                minioClient = MinioClient.builder()
                        .endpoint(endpoint)
                        .credentials(accessKey, secretKey)
                        .build();
                createBucket(bucketName);
                log.info("MinioClient 创建成功...");
            }
        } catch (Exception e) {
            log.error("MinioClient 创建失败...");
            e.printStackTrace();
        }
    }


    /**
     * 查看存储bucket是否存在
     * @return boolean
     */
    public static Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            return found;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 如果没有Bucket则创建
     * @throws Exception
     */
    private static boolean createBucket(String bucketName) throws Exception {
        if (bucketName == null || bucketName.isEmpty()) {
            log.error("Bucket name is null or empty.");
            return false;
        }

        try {
            // 检查存储桶是否存在
            if (!bucketExists(bucketName)) {
                // 创建存储桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                log.info("Bucket '{}' created successfully.", bucketName);
                return true;
            } else {
                log.info("Bucket '{}' already exists.", bucketName);
                return true; // 存储桶已存在，也视为成功
            }
        } catch (Exception e) {
            log.error("Failed to create bucket '{}'.", bucketName, e);
            return false; // 创建失败
        }
    }

    /**
     * 删除存储bucket
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() {
        try {
            List<Bucket> buckets = minioClient.listBuckets();
            return buckets;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 文件上传
     * @param objectName 文件名称
     * @param file       文件对象
     * @return 文件访问地址
     */
    public static String uploadFile(String objectName, MultipartFile file) {
        String url = "";
        try {
            // 上传文件
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            url = endpoint + "/" + bucketName + "/" + objectName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 预览图片
     * @param fileName
     * @return
    public String preview(String fileName){
        // 查看文件地址
        GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(prop.getBucketName()).object(fileName).method(Method.GET).build();
        try {
            String url = minioClient.getPresignedObjectUrl(build);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    *//**
     * 文件下载
     * @param fileName 文件名称
     * @param res response
     * @return Boolean
     *//*
    public void download(String fileName, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(prop.getBucketName())
                .object(fileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                // 设置强制下载不打开
                // res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    *//**
     * 查看文件对象
     * @return 存储bucket内文件对象信息
     *//*
    public List<Item> listObjects() {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(prop.getBucketName()).build());
        List<Item> items = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                items.add(result.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return items;
    }

    *//**
     * 删除
     * @param fileName
     * @return
     * @throws Exception
     *//*
    public boolean remove(String fileName){
        try {
            minioClient.removeObject( RemoveObjectArgs.builder().bucket(prop.getBucketName()).object(fileName).build());
        }catch (Exception e){
            return false;
        }
        return true;
    }
*/
}
